import qs from 'qs'
// import { checkOpenid } from '@/assets/js/utils'
import axios from 'axios'
import NProgress from 'nprogress/nprogress'
import 'nprogress/nprogress.css'
import router from '../../router/index'
import Vue from 'vue'
let vue = new Vue()
let instance = axios.create()
instance.defaults.transformRequest = [function (data) {
  return qs.stringify(data)
}]

// 是否正在刷新的标志
window.isRefreshing = false
// 存储请求的数组
// let refreshSubscribers = []

// 将所有的请求都push到数组中
// function subscribeTokenRefresh (cb) {
//   refreshSubscribers.push(cb)
// }

// 数组中的请求得到新的token之后自执行，用新的token去请求数据
// function onRrefreshed (token) {
//   refreshSubscribers.map(cb => cb(token))
// }

// 刷新token的过期时间判断
// function isRefreshTokenExpired () {
//   let oData = sessionStorage.getItem('timestamp') // 这是在登陆时候保存的时间戳
//   let nDta = new Date().getTime()
//   let stamp = nDta - oData
//   // let minutes = parseInt((stamp % (1000 * 60 * 60)) / (1000 * 60))
//   let minutes = parseInt(stamp / (1000 * 60))
//   return minutes
// }
export function getRefreshToken () { // 刷新token 注意这里用到的service
  let url = '/api/refresh'
  let param = {
    refreshToken: sessionStorage.getItem('refreshToken')
  }
  return instance.post(url, param, {
    headers: {
      'Authorization': 'Bearer-' + sessionStorage.getItem('accessToken')
    }
  })
    .then((res) => {
      return Promise.resolve(res.data)
    })
}

// 拦截器，拦截发送和接收
instance.interceptors.request.use(
  config => {
    config.headers['portal'] = 'platform'
    const authTk = sessionStorage.getItem('accessToken') // 本地保存的token
    if (authTk) {
      config.headers['Authorization'] = 'Bearer-' + authTk
    }
    // NProgress.start()
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
instance.interceptors.response.use(
  response => {
    // NProgress.done()
    if (response.data.code === 4030) {
      vue.$notify.error({
        title: '错误',
        message: '权限不足'
      })
    } else if (typeof response.data.code !== 'number') {
    // 4001 表示会话失效，需要跳转到登录页面
    } else if (response.data.code === 4001) {
      if (!localStorage.getItem('isTokenOutOfDate')) {
        localStorage.setItem('isTokenOutOfDate', true)
        vue.$notify.warning({
          title: '提示',
          message: '离开时间过长，请重新登录'
        })
        sessionStorage.clear()
        router.push({name: 'Login'})
        setTimeout(() => {
          localStorage.removeItem('isTokenOutOfDate')
        }, 5000)
      }
    } else if (response.data.code === 5000 && response.data.path === '/org/property') {
      let error = new Error('/org/property')
      throw error
    } else if (response.data.code !== 200) {
      // 如果是问卷权限冲突，并且当前的页面不是问卷列表页面，则跳转到问卷列表页面
      if (response.data.code === 3000) {
        vue.$notify.warning({
          title: '警告',
          message: response.data.message
        })
        setTimeout(() => {
          router.push({ name: 'appSurveyList' })
        }, 1000)
      } else {
        vue.$notify.error({
          title: '错误',
          message: response.data.message
        })
      }
    }
    return response
  },
  error => {
    console.log('走到错误的error===>', error.response)
    if (error.response.data.code === 2007) {
      // // 刷新token
      if (!window.errTimer) {
        window.errTimer = setTimeout(() => delete window.errTimer, 1000)
        console.log('window.errTimer： ', window.errTimer)
        getRefreshToken().then(res => {
          window.isRefreshing = false
          sessionStorage.setItem('accessToken', res.data.accessToken)
          sessionStorage.setItem('refreshToken', res.data.refreshToken)
          sessionStorage.setItem('timestamp', new Date().getTime())
          vue.$notify.error({
            title: '错误',
            message: '请重新再试'
          })
        }).catch(err => {
          this.handleError(err)
          // 清除本地保存的
          sessionStorage.removeItem('accessToken')
          // 开发时注释跳转Login
          router.replace({name: 'Login'})
        })
      }
    } else if (error.response.data.code === 2000 || error.response.data.code === 2012) {
      sessionStorage.removeItem('accessToken')
      // 开发时注释跳转Login
      router.replace({name: 'Login'})
    }
    NProgress.done()
    return Promise.reject(error.response)
  }
)

instance.defaults.timeout = 100000

export default instance
